package com.sky.task;

import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理订单支付超时 每分钟定时查找数据库中超时支付的订单
     * 15分钟后算超时
     */
    @Scheduled(cron = "0 0/1 * * * *")
    public void timrTask(){
        log.info("处理用户端订单超时支付的定时任务:{}",LocalDateTime.now());
        //根据订单状态及下单时间来查找超时订单
        Integer status = Orders.PENDING_PAYMENT;  //未支付 1
        LocalDateTime dateTime = LocalDateTime.now().plusMinutes(-15);
       List<Orders> ordersList = orderMapper.searchStatusAndOrderTimeLt(status,dateTime);
       log.info("查到的超时订单为:{}",ordersList);
        //把超时订单的订单状态及取消原因修改进数据库
        if (ordersList != null){
           for (Orders orders : ordersList) {
                   orders.setStatus(Orders.CANCELLED); //订单取消 6
                   orders.setCancelReason("订单支付超时");
                   orders.setCancelTime(LocalDateTime.now());
                   orderMapper.updateStatus(orders);
            }
        }
    }

    /**
     * 处理派送超时  超时自动完成
     * 每天凌晨一点刷新一次
     */
    @Scheduled(cron = "0 0 0/1 * * * ")
    public void TimeTask(){
        log.info("定时处理派送中的订单{}",LocalDateTime.now());
        Integer status = Orders.DELIVERY_IN_PROGRESS;
        LocalDateTime dateTime = LocalDateTime.now().plusMinutes(-60);
        List<Orders> ordersList = orderMapper.searchStatusAndOrderTimeLt(status, dateTime);
        log.info("查到的派送超时的订单数据为:{}",ordersList);
        if (ordersList != null){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED); //订单完成 5
                orders.setDeliveryTime(LocalDateTime.now());
                orderMapper.updateStatus(orders);
            }
        }
    }
}
